package com.ttxs.fileformathandling.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ttxs.apicommon.model.entity.User;
import com.ttxs.apicommon.model.entity.UserApiInfo;
import com.ttxs.fileformathandling.annotation.AuthCheck;
import com.ttxs.fileformathandling.common.*;
import com.ttxs.fileformathandling.constant.CommonConstant;
import com.ttxs.fileformathandling.constant.UserConstant;
import com.ttxs.fileformathandling.exception.BusinessException;
import com.ttxs.fileformathandling.exception.ThrowUtils;

import com.ttxs.fileformathandling.model.dto.userapiinfo.UserApiInfoAddRequest;
import com.ttxs.fileformathandling.model.dto.userapiinfo.UserApiInfoQueryRequest;
import com.ttxs.fileformathandling.model.dto.userapiinfo.UserApiInfoUpdateRequest;
import com.ttxs.fileformathandling.service.UserApiInfoService;
import com.ttxs.fileformathandling.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * user_api接口
 *
 */
@RestController
@RequestMapping("/user_api")
@Slf4j
public class UserApiController {

    @Resource
    private UserApiInfoService userApiInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param userApiInfoAddRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/add")
    public BaseResponse<Long> addUserApi(@RequestBody UserApiInfoAddRequest userApiInfoAddRequest, HttpServletRequest request) {
        if (userApiInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserApiInfo userApiInfo = new UserApiInfo();
        BeanUtils.copyProperties(userApiInfoAddRequest, userApiInfo);

        userApiInfoService.validUserApiInfo(userApiInfo, true);
        User loginUser = userService.getLoginUser(request);
        userApiInfo.setUserId(loginUser.getId());

        boolean result = userApiInfoService.save(userApiInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newApiId = userApiInfo.getId();
        return ResultUtils.success(newApiId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserApi(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserApiInfo oldUserApi = userApiInfoService.getById(id);
        ThrowUtils.throwIf(oldUserApi == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserApi.getUserId().equals(user.getId()) && userService.notAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = userApiInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param userApiInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserApi(@RequestBody UserApiInfoUpdateRequest userApiInfoUpdateRequest) {
        if (userApiInfoUpdateRequest == null || userApiInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserApiInfo userApiInfo = new UserApiInfo();
        BeanUtils.copyProperties(userApiInfoUpdateRequest, userApiInfo);

        // 参数校验
        userApiInfoService.validUserApiInfo(userApiInfo, false);
        long id = userApiInfoUpdateRequest.getId();
        // 判断是否存在
        UserApiInfo oldUserApi = userApiInfoService.getById(id);
        ThrowUtils.throwIf(oldUserApi == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = userApiInfoService.updateById(oldUserApi);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/get")
    public BaseResponse<UserApiInfo> getUserApiById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserApiInfo userApiInfo = userApiInfoService.getById(id);
        if (userApiInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(userApiInfo);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param userApiInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/list")
    public BaseResponse<List<UserApiInfo>> listUserApi(@RequestBody UserApiInfoQueryRequest userApiInfoQueryRequest) {
        UserApiInfo userApiInfo = new UserApiInfo();
        if (userApiInfoQueryRequest!=null){
            BeanUtils.copyProperties(userApiInfoQueryRequest,userApiInfo);
        }
        QueryWrapper<UserApiInfo> queryWrapper = new QueryWrapper<>(userApiInfo);
        List<UserApiInfo> userApiInfoList = userApiInfoService.list(queryWrapper);
        return ResultUtils.success(userApiInfoList);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param userApiInfoQueryRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/list/page")
    public BaseResponse<Page<UserApiInfo>> listUserApiByPage(@RequestBody UserApiInfoQueryRequest userApiInfoQueryRequest,
            HttpServletRequest request) {
        if (userApiInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserApiInfo userApiInfo = new UserApiInfo();
        BeanUtils.copyProperties(userApiInfoQueryRequest,userApiInfo);
        String sortField = userApiInfoQueryRequest.getSortField();
        String sortOrder = userApiInfoQueryRequest.getSortOrder();
        long current = userApiInfoQueryRequest.getCurrent();
        long size = userApiInfoQueryRequest.getPageSize();

        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        QueryWrapper<UserApiInfo> queryWrapper = new QueryWrapper<>(userApiInfo);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        Page<UserApiInfo> apiPage = userApiInfoService.page(new Page<>(current, size),queryWrapper);
        return ResultUtils.success(apiPage);
    }

}
